<template>
  <div class="main h-[calc(100%-29px)]">
    <div class="w-full">
      <div v-if="queryShow" class="mb-[10px] w-full search-form">
        <el-form :inline="true" :model="queryForm.data" label-width="0px">
          <el-form-item>
            <el-input
              v-model="queryForm.data.blurry"
              clearable
              placeholder="输入岗位名称搜索"
            />
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="queryForm.data.createTime"
              type="datetimerange"
              range-separator=":"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="queryForm.data.enabled"
              placeholder="状态"
              clearable
              style="width: 120px"
            >
              <el-option
                v-for="item in statusDict.data"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="ml-[10px]">
            <el-button type="primary" :icon="Search" @click="search"
              >搜索</el-button
            >
            <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="w-full">
        <div class="w-full flex justify-between">
          <div class="buttons flex align-center">
            <el-button type="primary" :icon="Plus" @click="addMenu"
              >新增</el-button
            >
            <el-button
              type="success"
              :icon="Edit"
              :disabled="!(multipleSelection.length === 1)"
              @click="editSelect"
              >修改</el-button
            >
            <el-button
              type="danger"
              :icon="Delete"
              :disabled="!multipleSelection.length"
              @click="delSelect"
              >删除</el-button
            >
            <el-button type="warning" :icon="Download" @click="exportData"
              >导出</el-button
            >
          </div>
          <div class="settings">
            <el-button-group class="ml-4">
              <el-button
                type="primary"
                :icon="Search"
                @click="queryShow = !queryShow"
              />
              <el-button type="primary" :icon="RefreshLeft" @click="getList" />
              <el-popover placement="bottom" :width="200" trigger="click">
                <template #reference>
                  <el-button type="primary" :icon="Grid" />
                </template>
                <el-checkbox
                  v-model="checkAll"
                  :indeterminate="isIndeterminate"
                  @change="handleCheckAllChange"
                  >全选</el-checkbox
                >
                <el-checkbox-group
                  v-model="checkedCities"
                  class="columns-show-group"
                  @change="handleCheckedCitiesChange"
                >
                  <el-checkbox
                    v-for="item in defaultColums.data"
                    :key="item.prop"
                    :label="item.prop"
                    >{{ item.label }}</el-checkbox
                  >
                </el-checkbox-group>
              </el-popover>
            </el-button-group>
          </div>
        </div>
        <div class="flex">
          <div class="role w-full">
            <div v-loading="loading" class="w-full mt-[10px]">
              <el-table
                ref="multipleTableRef"
                :data="tableData.data"
                style="width: 100%"
                row-key="id"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column
                  v-for="item in colums.data"
                  :key="item.prop"
                  :prop="item.prop"
                  :label="item.label"
                  :width="item.width"
                >
                  <template v-if="item.prop === 'enabled'" #default="scope">
                    <el-switch
                      v-model="scope.row.enabled"
                      :disabled="scope.row.username === 'admin'"
                      @change="switchChange(scope.row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="120">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      size="small"
                      :icon="Edit"
                      @click="editRow(scope.row)"
                    />
                    <el-popconfirm
                      width="200px"
                      title="确定删除本条数据吗？"
                      @confirm="delConfirm(scope.row)"
                    >
                      <template #reference>
                        <el-button type="danger" size="small" :icon="Delete" />
                      </template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="page w-full mt-[10px]">
              <el-pagination
                v-model:current-page="pageObj.data.currentPage"
                v-model:page-size="pageObj.data.pageSize"
                :page-sizes="[10, 20, 30, 40, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageObj.data.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="addDialog"
      :close-on-click-modal="false"
      :before-close="beforeClose"
      :title="title"
      width="580px"
    >
      <el-form
        ref="formRef"
        :model="form.data"
        :rules="form.rules"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.data.name" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="jobSort">
              <el-input-number
                v-model.number="form.data.jobSort"
                :min="0"
                :max="999"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="enabled">
              <el-radio
                v-for="item in statusDict.data"
                :key="item.id"
                v-model="form.data.enabled"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  Check,
  Delete,
  Download,
  Edit,
  Grid,
  Plus,
  RefreshLeft,
  Search
} from "@element-plus/icons-vue";
import {
  ElForm,
  ElMessageBox,
  ElNotification,
  ElTable,
  ElTree
} from "element-plus";
import { nextTick, onMounted, reactive, ref, toRaw } from "vue";
import {
  getCurrentLevel,
  getDictData,
  getJobList,
  ResultJob,
  exportJobList,
  editJobApi,
  delJobApi,
  addJobApi
} from "@/api/system";
import { cloneDeep } from "@pureadmin/utils";
import { downloadFile } from "@/utils";
const queryShow = ref(true);
const queryForm = reactive({
  data: {
    blurry: undefined,
    enabled: undefined,
    createTime: []
  }
});
const resetQuery = () => {
  queryForm.data = {
    blurry: undefined,
    enabled: undefined,
    createTime: []
  };
};
const search = async () => {
  pageObj.data.currentPage = 1;
  let { content, totalElements } = await getData();
  pageObj.data.total = totalElements;
  tableData.data = content;
};
const getList = async () => {
  let { content, totalElements } = await getData();
  pageObj.data.total = totalElements;
  tableData.data = content;
};
const exportData = async () => {
  let res = await exportJobList({
    page: pageObj.data.currentPage - 1,
    size: pageObj.data.pageSize,
    sort: "jobSort,asc",
    name: queryForm.data.blurry ? queryForm.data.blurry : undefined,
    enabled: queryForm.data.enabled ? queryForm.data.enabled : undefined,
    createTime: queryForm.data.createTime.length
      ? queryForm.data.createTime
      : undefined
  });
  downloadFile(res, "部门数据", "xlsx");
};
const handleSizeChange = () => {
  search();
};
const handleCurrentChange = async () => {
  getList();
};
const getData = () => {
  loading.value = true;
  return new Promise<ResultJob>(async (resolve, reject) => {
    let data = await getJobList({
      page: pageObj.data.currentPage - 1,
      size: pageObj.data.pageSize,
      sort: "jobSort,asc",
      name: queryForm.data.blurry ? queryForm.data.blurry : undefined,
      enabled: queryForm.data.enabled ? queryForm.data.enabled : undefined,
      createTime: queryForm.data.createTime.length
        ? queryForm.data.createTime
        : undefined
    });
    loading.value = false;
    resolve(data);
  });
};
const currentLevel = ref(3);
const statusDict = reactive({
  data: []
});
const init = async () => {
  const { level } = await getCurrentLevel();
  currentLevel.value = level;
  const { content } = await getDictData({
    dictName: "job_status",
    page: 0,
    size: 9999
  });
  statusDict.data = content;
};
init();
const tableData = reactive({
  data: []
});
const colums = reactive({
  data: [
    {
      label: "名称",
      prop: "name"
    },
    {
      label: "排序",
      prop: "jobSort"
    },
    {
      label: "状态",
      prop: "enabled"
    },
    {
      label: "创建日期",
      prop: "createTime",
      width: "200px"
    }
  ]
});
const defaultColums = reactive({
  data: [
    {
      label: "名称",
      prop: "name"
    },
    {
      label: "排序",
      prop: "jobSort"
    },
    {
      label: "状态",
      prop: "enabled"
    },
    {
      label: "创建日期",
      prop: "createTime",
      width: "200px"
    }
  ]
});
const switchChange = row => {
  ElMessageBox.confirm(
    `此操作将 "${!row.enabled ? "停用" : "启用"}" ${row.name}, 是否继续?`,
    "系统提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    }
  )
    .then(async () => {
      await editJobApi(row);
      ElNotification({
        title: "系统提示",
        message: !row.enabled ? "停用成功" : "启用成功",
        type: "success"
      });
      // search();
    })
    .catch(() => {
      row.enabled = !row.enabled;
    });
};
const loading = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref([]);
const checkAll = ref(true);
const isIndeterminate = ref(false);
const checkedCities = ref([]);

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? defaultColums.data.map(item => item.prop) : [];
  isIndeterminate.value = false;
  if (checkedCities.value.length) {
    colums.data = defaultColums.data;
  } else {
    colums.data = [];
  }
};
const pageObj = reactive({
  data: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  }
});
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === defaultColums.data.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < defaultColums.data.length;
  let cols = [];
  defaultColums.data.forEach(i => {
    if (value.indexOf(i.prop) > -1) {
      cols.push(i);
    }
  });
  colums.data = cols;
};
onMounted(() => {
  search();
  checkedCities.value = colums.data.map(item => item.prop);
});
const props = {
  label: "label",
  hasChildren: "hasChildren",
  children: "children",
  isLeaf: "leaf"
};
const form = reactive({
  data: {
    id: null,
    name: "",
    jobSort: 999,
    enabled: true
  },
  rules: {
    name: [{ required: true, message: "请输入名称", trigger: "blur" }],
    jobSort: [
      { required: true, message: "请输入序号", trigger: "blur", type: "number" }
    ]
  }
});
const addDialog = ref(false);
const title = ref("新增岗位");
const status = ref("add");
const addMenu = () => {
  addDialog.value = true;
  title.value = "新增岗位";
  status.value = "add";
  form.data.enabled = "true";
};
const handleSelectionChange = val => {
  multipleSelection.value = val;
};
const editRow = async row => {
  addDialog.value = true;
  title.value = "编辑岗位";
  status.value = "edit";
  let data = cloneDeep(row);
  data.enabled = `${data.enabled}`;
  form.data = data;
};
const delSelect = () => {
  if (multipleSelection.value.length) {
    ElMessageBox.confirm(
      `确认删除选中的${multipleSelection.value.length}条数据?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    ).then(async () => {
      await delJobApi(multipleSelection.value.map(i => i.id));
      ElNotification({
        title: "系统提示",
        message: "删除成功",
        type: "success"
      });
      search();
    });
  }
};
const editSelect = () => {
  if (multipleSelection.value.length === 1) {
    editRow(multipleSelection.value[0]);
  }
};
const formRef = ref<InstanceType<typeof ElForm>>();
const resetForm = () => {
  form.data = {
    id: null,
    name: "",
    jobSort: 999,
    enabled: true
  };
  nextTick(() => {
    formRef.value.resetFields();
  });
};
const beforeClose = d => {
  form.data = {
    id: null,
    name: "",
    jobSort: 999,
    enabled: true
  };
  nextTick(() => {
    d();
  });
};
const cancel = () => {
  form.data = {
    id: null,
    name: "",
    jobSort: 999,
    enabled: true
  };
  formRef.value.resetFields();
  nextTick(() => {
    addDialog.value = false;
  });
};
const submit = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      let data = cloneDeep(form.data);
      if (status.value === "add") {
        await addJobApi(data);
        ElNotification({
          title: "系统提示",
          message: "岗位创建成功",
          type: "success"
        });
      } else {
        await editJobApi(data);
        ElNotification({
          title: "系统提示",
          message: "岗位编辑成功",
          type: "success"
        });
      }
      resetForm();
      nextTick(() => {
        addDialog.value = false;
        search();
      });
    }
  });
};
const delConfirm = async row => {
  await delJobApi([row.id]);
  ElNotification({
    title: "系统提示",
    message: "删除成功",
    type: "success"
  });
  search();
};
</script>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

.main-content {
  //margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-right: 4px;
    margin-bottom: 0;
  }
}
</style>
